interface ColorList {
  color: string
  darkColor: string
  className: string
}

function isDark() {
  // 主题判断
  let theme

  // user-agent传参确定主题
  let userAgent = navigator.userAgent
  theme = userAgent.includes('Theme/Night') ? 'dark' : 'light'

  // 路径传参确定主题
  const url = new URL(location.href)
  const regex = /[?|&]mode=night/g
  if (regex.test(url.href)) {
    theme = 'dark'
  }

  return theme === 'dark'
}

function addStyle(lists: ColorList[], cssName: string, isDark: boolean) {
  let style = ''

  lists.forEach((value) => {
    let color = isDark ? value.darkColor : value.color
    style += `.${value.className} {${cssName}: ${color}}`
  })

  return style
}

export function addColor() {
  const bgColorList: ColorList[] = [
    {
      color: '#f7f7f7',
      darkColor: '#1d1e1e',
      className: 'mm-bg-color-1'
    },
    {
      color: '#ffffff',
      darkColor: '#272829',
      className: 'mm-bg-color-2'
    }
  ]

  const borderColorList: ColorList[] = [
    {
      color: '#efefef',
      darkColor: '#4b4c4d',
      className: 'mm-bg-color-3'
    },
    {
      color: '#e5e5e5',
      darkColor: '#303030',
      className: 'mm-line-bg-color'
    }
  ]

  const map = new Map().set('bgColorList', bgColorList).set('borderColorList', borderColorList)

  let colorList = ''
  map.forEach((value, key) => {
    if (key.includes('bgColorList')) {
      colorList += addStyle(value, 'background-color', true)
    }
    if (key.includes('borderColorList')) {
      colorList += addStyle(value, 'border-color', true)
    }
  })

  const styleElement = document.createElement('style')
  styleElement.innerText = colorList
  const html = document.querySelector('head')
  html?.append(styleElement)
}
